package datastructure.ch01_base;

/**
 * 斐波那契数列
 * F(0) = 0，F(1) = 1
 * F(n) = F(n - 1) + F(n - 2)，其中 n > 1
 * 0 1 2 3 4 5
 * 0 1 1 2 3 5 8 13 21...
 *
 * @author guodd
 * @version 1.0 use jdk 1.8
 */
public class FibSolution {
    public static void main(String[] args) {
        System.out.println(fib01(8));
        System.out.println(fib02(8));
        System.out.println(fib03(8));
    }

    /**
     * 递归方式O(2^n)
     *
     * @param n
     * @return
     */
    public static int fib01(int n) {
        if (n <= 1)
            return n;
        // O(2^n)
        return fib01(n - 1) + fib01(n - 2);
    }

    /**
     * 循环计算O(n)
     *
     * @param n
     * @return
     */
    public static int fib02(int n) {
        if (n <= 1)
            return n;
        int first = 0;
        int second = 1;
        // 1 + (n - 1) + n + 3n
        // 5n
        // O(n)
        for (int i = 0; i < n - 1; i++) {
            int sum = first + second;
            first = second;
            second = sum;
        }
        return second;
    }

    public static int fib03(int n) {
        if (n <= 1) return n;

        int first = 0;
        int second = 1;
        // 省略变量
        while (n-- > 1) {
            second += first;
            first = second - first;
        }
        return second;
    }

    /**
     * 线性代数解法-特征方程 O(1)
     *
     * @param n 第几个数
     * @return 计算值
     */
    public static int fib04(int n) {
        double c = Math.sqrt(5);
        return (int) ((Math.pow((1 + c) / 2, n) - Math.pow((1 - c) / 2, n)) / c);
    }
}
